package com.lry.block;

import com.lry.it.BlockIterator;
import com.lry.it.SeekingIterable;
import com.lry.it.SeekingIterator;
import com.lry.util.Slice;
import com.lry.util.Slices;

import java.util.Comparator;

import static com.google.common.base.Preconditions.checkArgument;
import static com.lry.util.SizeOf.SIZE_OF_INT;
import static java.util.Objects.requireNonNull;

public class Block implements SeekingIterable<Slice,Slice> {

    private final Slice block;//整个block
    private final Comparator<Slice> comparator;

    private final Slice data;//block的数据段
    private final Slice restartPositions;//block的索引段

    public Block(Slice block,Comparator<Slice> comparator){
        requireNonNull(block, "block is null");
        checkArgument(block.length() >= SIZE_OF_INT, "Block is corrupt: size must be at least %s block", SIZE_OF_INT);
        requireNonNull(comparator, "comparator is null");

        block = block.slice();
        this.block = block;
        this.comparator = comparator;

        //拿到整个block最后一个int，该值表示group的个数
        int restartCount = block.getInt(block.length() - SIZE_OF_INT);

        if(restartCount>0){
            //确定索引的开始偏移
            int restartOffset = block.length() - (1+restartCount)*SIZE_OF_INT;
            checkArgument(restartOffset < block.length() - SIZE_OF_INT, "Block is corrupt: restart offset count is greater than block size");

            restartPositions = block.slice(restartOffset, restartCount * SIZE_OF_INT);
            data = block.slice(0, restartOffset);
        }else{
            data = Slices.EMPTY_SLICE;
            restartPositions = Slices.EMPTY_SLICE;
        }
    }


    public long size()
    {
        return block.length();
    }

    @Override
    public BlockIterator iterator() {
        return new BlockIterator(data, restartPositions, comparator);
    }

}
